#import "TSSpiltTaskController.h"
#import "TSSpilteTableView.h"
#import "TSMutipleCheckTableViewController.h"
#import "TSTaskModel.h"
#import "TSMsgContentItemCell.h"
#import "TSMsgDatePickerTextFieldCell.h"
#import "TSPickerViewTextFieldCell.h"
#import "TStaskModel.h"
#import "TSEditContentController.h"


@implementation TSSpiltTaskController{
    UIView * container;
    TSSpilteTableView *tableView;
    TSTaskModel *taskModel;
}

@synthesize taskId,enclosurePath,mTaskModel;

- (void)viewDidLoad
{
    [super viewDidLoad];
    taskModel = [[TSTaskModel alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentViewController:) name:TSNotification_PresentViewController object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectedEnclosure:) name:TSNotification_Selected_Enclosure object:nil];
    self.title = @"拆分任务";
    WS(weakSelf);
    [self rightBarButtonWithTitle:@"" barNorImage:[UIImage imageNamed:@"topic_follow_add"] barHltImage:nil action:^{
        if (!weakSelf) {
            return;
        }
        [weakSelf rightClick];
    }];
    
    tableView = [[TSSpilteTableView alloc] initWithFrame:CGRectMake(0, 0, currentDeviceWidth, currentDeviceHeight-110)];
    [tableView initData:mTaskModel];
    [self.view addSubview:tableView];
    
}

/* 拆分 */
- (void)rightClick
{
    UIActionSheet *action_sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"完成",@"保存",@"添加节点", nil];
    [action_sheet showInView:self.view];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        //完成
        [self insertMsg];
    }else if (buttonIndex == 1) {
        [self save];
    }else if (buttonIndex == 2) {
        [tableView addNewNode];
    }
}

-(BOOL)checkCanSend
{
//    if ([TSTools isEmpty:[self getContentByTitle:@"标题:"]]) {
//        [TSTools showAlert:@"请输入标题"];
//        return false;
//    }
//    //    if ([TSTools isEmpty:[self getContentByTitle:@"内容:"]]) {
//    //        [TSTools showAlert:@"请输入内容"];
//    //        return false;
//    //    }
//    if ([TSTools isEmpty:[self getContentByTitle:@"主办人:"]]) {
//        [TSTools showAlert:@"请选择主办人"];
//        return false;
//    }
//    if ([TSTools isEmpty:[self getContentByTitle:@"监督人:"]]) {
//        [TSTools showAlert:@"请选择监督人"];
//        return false;
//    }
//    if ([TSTools isEmpty:[self getContentByTitle:@"审核人:"]]) {
//        [TSTools showAlert:@"请选择审核人"];
//        return false;
//    }
    return true;
    
}

-(void)save{
    WS(weakSelf);
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:10];
    [dictionary setObject:taskId forKey:@"id"];
    for(int i=0; i<tableView.nodeCount;i++){
        [dictionary setObject:[self getContentByTitle:@"标题:" section:i] forKey:[NSString stringWithFormat:@"title[%d]",i]];
        [dictionary setObject:[self getContentByTitle:@"内容:" section:i] forKey:[NSString stringWithFormat:@"content[%d]",i]];
        [dictionary setObject:[tableView.userArray objectAtIndex:i] forKey:[NSString stringWithFormat:@"receiveId[%d]",i]];
        [dictionary setObject:[self getContentByTitle:@"开始时间:" section:i] forKey:[NSString stringWithFormat:@"timeBegin[%d]",i]];
        [dictionary setObject:[self getContentByTitle:@"结束时间:" section:i] forKey:[NSString stringWithFormat:@"timeEnd[%d]",i]];
        
    }
    
    taskModel.requestParams = dictionary;
    
    [taskModel fetchWithPath:kRequestUrl_Task_Split_Save completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        
        if (isSucceeded) {
            [[LBToastManager manager] showtoast:@"保存成功!"];
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:TSNotification_MessagePostSucceeded object:nil];
        }
        else{
            [[LBToastManager manager] showtoast:@"保存失败!"];
        }
        
    } NoProgress:NO];
}

- (void)insertMsg
{
    WS(weakSelf);
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:10];
    [dictionary setObject:taskId forKey:@"id"];
    for(int i=0; i<tableView.nodeCount;i++){
        [dictionary setObject:[self getContentByTitle:@"标题:" section:i] forKey:[NSString stringWithFormat:@"title[%d]",i]];
        [dictionary setObject:[self getContentByTitle:@"内容:" section:i] forKey:[NSString stringWithFormat:@"content[%d]",i]];
        [dictionary setObject:[tableView.userArray objectAtIndex:i] forKey:[NSString stringWithFormat:@"receiveId[%d]",i]];
        [dictionary setObject:[self getContentByTitle:@"开始时间:" section:i] forKey:[NSString stringWithFormat:@"timeBegin[%d]",i]];
        [dictionary setObject:[self getContentByTitle:@"结束时间:" section:i] forKey:[NSString stringWithFormat:@"timeEnd[%d]",i]];
        
    }

    taskModel.requestParams = dictionary;
    
    [taskModel fetchWithPath:kRequestUrl_Task_Split_Save completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        
        if (isSucceeded) {
            [[LBToastManager manager] showtoast:@"保存成功!"];
            [taskModel fetchWithPath:kRequestUrl_Task_Split_Send completionHandler:^(BOOL isSucceeded, NSError *error) {
                if (!weakSelf) {
                    return;
                }
                
                if (isSucceeded) {
                    [[LBToastManager manager] showtoast:@"拆分成功!"];
                    [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                    [[NSNotificationCenter defaultCenter] postNotificationName:TSNotification_MessagePostSucceeded object:nil];
                }
                else{
                    [[LBToastManager manager] showtoast:@"拆分失败!"];
                }
                
            } NoProgress:NO];

        }
        else{
            [[LBToastManager manager] showtoast:@"保存失败!"];
        }
        
    } NoProgress:NO];
}

- (NSString *)getContentByTitle:(NSString *)title section:(NSInteger)section
{
    //    @[@"标题:", @"时间:", @"地点:", @"内容:", @"发送人:", @"接收人:", @"审核人:", @"附件:", @"时限:"];
    
    NSString *content = @"";
    UITableViewCell *cell = [tableView getCellByTitle:title section:section];
    

    if ([cell isKindOfClass:[TSMsgContentItemCell class]]) {
        TSMsgContentItemCell *item_cell = (TSMsgContentItemCell *)cell;
        content = item_cell.contentTextField.text;
    }
    else if ([cell isKindOfClass:[TSMsgDatePickerTextFieldCell class]]){
        TSMsgDatePickerTextFieldCell *date_cell = (TSMsgDatePickerTextFieldCell *)cell;
        /* default selectd item */
        NSDateFormatter *format = [[NSDateFormatter alloc] init];
        [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        content = [format stringFromDate:date_cell.contentTextField.datePicker
         .date];
    }
    else if ([cell isKindOfClass:[TSPickerViewTextFieldCell class]]){
        TSPickerViewTextFieldCell *picker_cell = (TSPickerViewTextFieldCell *)cell;
        content = picker_cell.contentTextField.text;
    }
    
    return content;
}

- (void)presentViewController:(NSNotification *)noti
{
    NSNumber *type = noti.object;
    if(type.integerValue == ToolBarTextField_Type_Content){
        TSEditContentController *edit_vc = [[TSEditContentController alloc] init];
        TSBaseNavigationController *nav = [[TSBaseNavigationController alloc] initWithRootViewController:edit_vc];
          edit_vc.section = [[noti.userInfo objectForKey:@"section"] intValue];
        edit_vc.content = [self getContentByTitle:@"内容:" section:edit_vc.section ];
      
        [self presentViewController:nav animated:YES completion:nil];
    }else{
        TSMutipleCheckTableViewController *multiple_vc = [[TSMutipleCheckTableViewController alloc] init];
        multiple_vc.toolBarTextFieldType = type.integerValue;
         multiple_vc.section = [[noti.userInfo objectForKey:@"section"] intValue];
        TSBaseNavigationController *nav = [[TSBaseNavigationController alloc] initWithRootViewController:multiple_vc];
        [self presentViewController:nav animated:YES completion:nil];
    }
    
}

-(void)selectedEnclosure:(NSNotification *)noti
{
    self.enclosurePath = noti.object;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

